package com.bo.Dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bo.Dao.ProductCommentDao;
import com.bo.Entity.Comment;

 
@Repository
public class ProductCommentDaoImpl implements ProductCommentDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;
	


	public int save(Comment comment){
		
		String sql="insert into product_comment(rate,content,time,product_id) value (?,?,?,?)";
		
		return jdbcTemplate.update(sql,comment.getRate(),comment.getContent()
				                           ,comment.getTime(),comment.getProductId());
		
	}
	
	

	public List<Comment> getAllComment(int productId){
		
		return this.jdbcTemplate.query("select rate,content,time from product_comment where product_id=? order by time"
				                                               , new RowMapper<Comment>(){

			public Comment mapRow(ResultSet rs, int rowNum) throws SQLException {
  
                Comment com=new Comment();
                
                com.setRate(rs.getDouble("rate"));
                com.setContent(rs.getString("content"));
                com.setTime(rs.getString("time"));
               
				return com;
			}
		},productId);
	}
	
	
	
	
	public Double getAverageRating(int productId){
		
		
		return this.jdbcTemplate.queryForObject("select avg(rate) from product_comment where product_id=?", new Object[]{productId}, Double.class);
		
	}
	
}
